#include <iostream>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

void DrawHorn(Mat& src, vector<Rect>& face, Mat& horn, Mat& mask)
{
    if(face.empty())
        return ;

    for(int i = 0; i < face.size(); i++)
    {
        if (((face[i].tl().x + horn.cols) >= src.cols)
                || ((face[i].tl().y + horn.rows) >= src.rows)
                || face[i].tl().x < 0 || face[i].tl().y - 80 < 0)
            continue;
        Mat ROI = src(Rect(face[i].tl().x, face[i].tl().y - 80, horn.cols, horn.rows));
        horn.copyTo(ROI, mask);       //把龙角复制到兴趣区域（头上）
    }
}

int main(int argc, char *argv[])
{
    VideoCapture cap = VideoCapture(0);    //读取视频，并保存到cap对象中

    Mat img;
    vector<Rect> face;
    CascadeClassifier object;
    object.load("d:/work/haarcascade_frontalface_alt.xml");

    Mat horn = imread("d:/work/horn.png");
    Mat mask = imread("d:/work/horn.png", 0);

    while(cap.read(img))   //循环读取视频的每一帧
    {
        face.clear();   //清空已检测到的人脸
        object.detectMultiScale(img, face);
        //DrawRect(img, face);
        DrawHorn(img, face, horn, mask);
        imshow("video", img);   //显示每一帧的图像
        waitKey(30);
    }
    cap.release();  //释放视频
    cout << "Hello World!" << endl;
    return 0;
}
